<template>
  <div>
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item prop="name" label="部门名称">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item prop="code" label="部门编码">
        <el-input v-model="form.code" />
      </el-form-item>
      <el-form-item prop="manager" label="部门负责人">
        <el-select v-model="form.manager" placeholder="请选择负责人">
          <!-- <el-option label="区域一" value="shanghai" />
          <el-option label="区域二" value="beijing" /> -->
          <el-option v-for="item in userList" :key="item.id" :label="item.username" :value="item.username" />
        </el-select>
      </el-form-item>
      <el-form-item prop="introduce" label="部门介绍">
        <el-input v-model="form.introduce" type="textarea" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">{{ isEdit?'编辑':'新增' }}</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getUserSimpleRequest } from '@/api/employees'
import { addDepartmentRequest, getDeparmentByIdRequest, updateDepartmentByIdRequest } from '@/api/department'
export default {
  name: 'VueZzwHrUpdateDialog',
  props: {
    currentId: {
      type: String,
      default: ''
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    arrListToChild: {
      type: Array,
      // 默认值为复杂数据类型的时候,不能直接写[]|{}这种,因为会把地址写死,我们每次通过函数返回新地址
      default: () => []
    }
  },
  data() {
    // this值只要有个函数.name函数调用的时候就会动态创建一个变量,名叫this
    // 方法一:用箭头函数来避免this指向错误问题
    // 方法二:用 that = this 也可以解决
    const validateCode = (rule, value, callback) => {
      let codeList = this.arrListToChild.map(item => item.code)
      // console.log('部门编码列表', codeList)
      // console.log('code非空校验', value)
      // value值为用户输入部门编码的数据,如果用户未输入我们进行非空校验
      if (!value) {
        return callback(new Error('code码必填'))
      }
      if (this.isEdit) {
        codeList = this.arrListToChild.filter(item => item.id !== this.currentId).map(item => item.code)
        // console.log('编辑框', codeList)
      }
      // 当用户输入但输入的部门编码已存在的话提示用户重新输入
      if (codeList.includes(value)) {
        callback(new Error(`部门编码${value}已存在,请重新填写`))
      } else {
        // 自定义函数callback必须调用否者校验不执行
        callback()
      }
    }
    const validateName = (rule, value, callback) => {
      let nameList = this.arrListToChild.filter(item => item.pid === this.currentId).map(item => item.name)
      if (this.isEdit) {
        const editParent = this.arrListToChild.find(item => item.id === this.currentId)
        // console.log(editParent)
        const brother = this.arrListToChild.filter(item => item.id === editParent.pid)
        // console.log(brother)
        nameList = brother.filter(item => item.id !== this.currentId).map(item => item.name)
      }
      // console.log(nameList)
      if (nameList.includes(value)) {
        callback(new Error(`部门编码${value}已存在,请重新填写`))
      } else {
        // 自定义函数callback必须调用否者校验不执行
        callback()
      }
    }
    return {
      name: '',
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' },
          { validator: validateName, required: true, trigger: 'blur' }
        ],
        //
        code: [
          // { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' },
          { validator: validateCode, required: true, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '请输入负责人', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      },
      userList: []
    }
  },
  created() {
    // console.log('组件创建')
    this.getUserSimple()
    this.getDeparmentById()
  },
  methods: {
    onSubmit() {
      // 兜底校验
      this.$refs.form.validate(v => {
        if (v) {
          if (this.isEdit) {
            // console.log(this.isEdit)
            this.updateDepartmentById()
          } else {
            // console.log(this.isEdit)
            this.addDepartments()
          }
        }
      })
    },
    async getUserSimple() {
      try {
        const res = await getUserSimpleRequest()
        this.userList = res.data
        // console.log(res)
      } catch (error) {
        console.log('获取用户信息列表失败', error)
      }
    },
    // 根据点击部门的id判断如果是编辑状态则将数据回显
    async getDeparmentById() {
      if (this.isEdit) {
        const res = await getDeparmentByIdRequest(this.currentId)
        // console.log(res)
        this.form = res?.data
      }
    },
    cancel() {
      this.$emit('closeEvent')
    },
    async addDepartments() {
      try {
        const res = await addDepartmentRequest({ ...this.form, pid: this.currentId })
        // console.log(res)
        if (res.success) {
          this.$emit('success')
        } else {
          this.$message.error(res.message)
        }
      } catch (error) {
        console.log('添加信息失败!', error)
      }
    },
    async updateDepartmentById() {
      // console.log(this.form)
      const res = await updateDepartmentByIdRequest(this.form)
      if (res.success) {
        // console.log(res)
        this.$emit('success')
      } else {
        this.$message.error(res.message)
      }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
